package com.sk.myview;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import com.sk.water.R;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

public class ImageUpload extends LinearLayout {
	private Button addImage, commit;
	private LinearLayout imageGroup;
	private Context context;
	private Bitmap bitmap;
	private int configID;
	private final String SdStatus = Environment.getExternalStorageState();
	private final String FoldPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Water";
	private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
	private String fileFullPath;
	private String fileName;
	private Uri fileUri;
	private ImageView imageView;
	private List<HashMap<String, String>> imageList = new ArrayList<HashMap<String, String>>();
	private View deleteConfirmView;
	private View showBigImageView;
	private Gallery imageGallery;
	private File file;
	
	
	public ImageUpload(Context context) {
		super(context);		
		LayoutInflater.from(context).inflate(R.layout.image_upload, this);
		initialize(context);
	}

	public ImageUpload(Context context, AttributeSet attributeSet) {
		super(context, attributeSet);
		LayoutInflater.from(context).inflate(R.layout.image_upload, this);
		initialize(context);
	}
	
	public void setConfigID(int configID){
		this.configID = configID;
	}
	public int getConfigID(){
		return configID;
	}

	public void initialize(Context context) {
		this.context = context;
		this.addImage = (Button) findViewById(R.id.image_upload_addimage);
		this.commit = (Button) findViewById(R.id.image_upload_commit);
		this.imageGroup = (LinearLayout) findViewById(R.id.image_upload_imageview_group);

		File fileFold = new File(FoldPath);
		if(!fileFold.exists()){
			fileFold.mkdirs();
		}
		fileName = simpleDateFormat.format(Calendar.getInstance(Locale.CHINA).getTime())+ ".jpg";
		fileFullPath = FoldPath +"/"+ fileName;
		ClickEvent clickEvent = new ClickEvent();
		addImage.setOnClickListener(clickEvent);
		commit.setOnClickListener(clickEvent);

	}
	
	public File getFile(){
		return file;
	}
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			if(requestCode==0){
				if (!SdStatus.equals(Environment.MEDIA_MOUNTED)) {
					Log.v("TestFile","SD card is not avaiable/writeable right now.");
					return;
				}
				Bundle bundle = data.getExtras();
				Uri uri = data.getData();
				bitmap = (Bitmap) bundle.get("data");
//				byte [] temp  = Bitmap.
				FileOutputStream b = null;
				fileName = simpleDateFormat.format(Calendar.getInstance(Locale.CHINA).getTime())+ ".jpg";
				fileFullPath = FoldPath +"/"+ fileName;
				try {
					b = new FileOutputStream(fileFullPath);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
						
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
				file = new File(fileFullPath);
				ContentResolver contentResolver = context.getContentResolver();
				fileUri = Uri.parse(MediaStore.Images.Media.insertImage(contentResolver, bitmap, null, null));
			//	bitmap.recycle();
		 	}else if(requestCode==1) {
				ContentResolver cr = context.getContentResolver();
				String [] pathStrings = {MediaStore.Images.Media.DATA};
				fileUri = data.getData();
				Cursor cursor = cr.query(fileUri, pathStrings, null, null, null);
				int cursorindex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();				
				fileFullPath = cursor.getString(cursorindex);
				cursor.close();								
				file = new File(fileFullPath);
			}						
											
	//		HashMap<String, String> imageHashMap = new HashMap<String, String>();
	//		imageHashMap.put("path", fileFullPath.toString());
	//		imageHashMap.put("uri", fileUri.toString());
	//		imageList.add(imageHashMap);
	//		refreshImageGroup();
			
		}
		
	}
	
	
	
	public List<HashMap<String, String>> returnPicturs(){
		return imageList;
	}			
	public void refreshImageGroup(){
		imageGroup.removeAllViews();
		for (int i = 0; i < imageList.size(); i++) {
			imageView = new ImageView((Activity) context);
			imageView.setLayoutParams(new LayoutParams(100, 100));
			final Uri uri = Uri.parse(imageList.get(i).get("uri"));
			imageView.setImageURI(uri);
			
			imageGroup.addView(imageView);
			
			final DeleteConfirm deleteConfirm = new DeleteConfirm((Activity)ImageUpload.this.context);
			deleteConfirm.setConfigID(i);
			
			final BigImage bigImage = new BigImage((Activity)ImageUpload.this.context);
			bigImage.setConfigID(i);
			
			
			imageView.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					
					bigImage.showAtLocation(LayoutInflater.from(context).inflate(R.layout.image_upload, null), Gravity.CENTER, 0, 0);
					
				}
			});
			imageView.setOnLongClickListener(new OnLongClickListener() {
				public boolean onLongClick(View v) {										
					deleteConfirm.showAtLocation(LayoutInflater.from(context).inflate(R.layout.image_upload, null), Gravity.BOTTOM, 0, 0);
					return true;
				}
			});							
		}		
	}
	
	private class ClickEvent implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.image_upload_addimage:
				MyPopupWindow myPopupWindow = new MyPopupWindow((Activity)context,fileFullPath);
				myPopupWindow.showAtLocation(LayoutInflater.from(context).inflate(R.layout.image_upload, null), Gravity.BOTTOM, 0, 0);				
				break;
			case R.id.image_upload_commit:
				returnPicturs();	
				break;

			default:
				break;
			}
		}
	}
	private class DeleteConfirm extends PopupWindow{
		private int imageID;
		public DeleteConfirm(Context context){
			super(context);
			deleteConfirmView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.long_click_popupwindow, null);
			setContentView(deleteConfirmView);
			this.setWidth(LayoutParams.MATCH_PARENT);
			this.setHeight(LayoutParams.MATCH_PARENT);
			this.setAnimationStyle(R.style.PopupAnimation);
			this.setFocusable(true);
			ColorDrawable dw = new ColorDrawable(0xb0000000);
			this.setBackgroundDrawable(dw);
			Button delete = (Button)deleteConfirmView.findViewById(R.id.btn_delete_photo);
			Button cancel = (Button)deleteConfirmView.findViewById(R.id.btn_delete_cancel);
			deleteConfirmView.setOnTouchListener(new OnTouchListener() {				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					int height = deleteConfirmView.findViewById(R.id.btn_delete_top).getTop();
					int y=(int) event.getY();
					if(event.getAction()==MotionEvent.ACTION_UP){
						if(y<height){
							dismiss();
						}
					}				
					return true;
				}
			});			
			cancel.setOnClickListener(new OnClickListener() {				
				public void onClick(View v) {
					dismiss();					
				}
			});
			delete.setOnClickListener(new OnClickListener() {				
				public void onClick(View v) {
					dismiss();
					int id = getConfigID();
					imageList.remove(id);
					imageGroup.removeViewAt(id);
							
				}
			});
		}
		public int getConfigID(){
			return imageID;
		}
		public void setConfigID(int configID){
			this.imageID = configID;
		}
	}
	
	private class BigImage extends PopupWindow{
		private int bigImageID;
		public BigImage(Context context){
			super(context);
			LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			showBigImageView = layoutInflater.inflate(R.layout.bigimage_popupwindow,null);
			setContentView(showBigImageView);
			this.setWidth(LayoutParams.MATCH_PARENT);
			this.setHeight(LayoutParams.MATCH_PARENT);
			this.setAnimationStyle(R.style.PopupAnimation);
			this.setFocusable(true);
			imageGallery = (Gallery)showBigImageView.findViewById(R.id.big_image_gallery);			
			ImageAdapter adapter = new ImageAdapter(context);		
			imageGallery.setAdapter(adapter);
			imageGallery.setSelection(getConfigID(),true);
		}
		public int getConfigID(){
			return bigImageID;
		}
		public void setConfigID(int configID){
			this.bigImageID = configID;
			imageGallery.setSelection(configID, true);
		}
	}
	
	private class ImageAdapter extends BaseAdapter{

		public ImageAdapter(Context context){
			super();
		}
		
		@Override
		public int getCount() {
			return imageList.size();
		}

		@Override
		public Object getItem(int position) {
			return imageList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = new ImageView(context);
			imageView.setImageURI(Uri.parse(imageList.get(position).get("uri")));
			imageView.setScaleType(ScaleType.FIT_CENTER);
			imageView.setLayoutParams(new android.widget.Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
			return imageView;
		}
		
	}
	
	
	
	
	public Bitmap changeURItoBitmap(Uri uri){		
		ContentResolver cr = context.getContentResolver();
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return bitmap;		
	}
	public Uri changeBitmaptoURI(Bitmap bitmap){
		ContentResolver cr = context.getContentResolver();
		Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(cr, bitmap, null, null));
		return uri;
	}
	public String changeURItoPath(Uri uri){		
		String bitmapPath=null;
		String [] object = {MediaStore.Images.Media.DATA};
		ContentResolver cr = context.getContentResolver();
		Cursor cursor = cr.query(uri, object, null, null, null);
		cursor.moveToFirst();
		int cursorIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
		bitmapPath = cursor.getString(cursorIndex);
		return bitmapPath;
	}
	public Bitmap getBitmapByPath(String path){
		Bitmap bitmap = BitmapFactory.decodeFile(path);
		return bitmap;
	}
}
